#include "ohos_init.h"
#include "cmsis_os2.h"

/* 互斥锁句柄 */
osMutexId_t g_testMux;
/* 任务ID */
osThreadId_t g_testTaskId01;
osThreadId_t g_testTaskId02;

// 修改任务函数签名（添加void*参数）
void Example_MutexTask1(void *argument) {
    (void)argument;  // 明确标记未使用参数
    osStatus_t ret;

    printf("task1 try to get mutex, wait 10 ticks.\n");
    /* 申请互斥资源（10 ticks超时） */
    ret = osMutexAcquire(g_testMux, 10);

    if (ret == osOK) {
        printf("task1 get mutex g_testMux.\n");
        /* 释放互斥资源 */
        osMutexRelease(g_testMux);
        return;
    } else if (ret == osErrorTimeout) {
        printf("task1 timeout and try to get mutex, wait forever.\n");
        /* 永久等待获取互斥锁 */
        ret = osMutexAcquire(g_testMux, osWaitForever);
        if (ret == osOK) {
            printf("task1 wait forever, get mutex g_testMux.\n");
            /* 释放互斥资源 */
            osMutexRelease(g_testMux);
            osThreadSuspend(g_testTaskId01);  // CMSIS挂起API
        }
    }
}

void Example_MutexTask2(void *argument) {
    (void)argument;
    printf("task2 try to get mutex, wait forever.\n");
    /* 永久等待获取互斥锁 */
    (void)osMutexAcquire(g_testMux, osWaitForever);

    printf("task2 get mutex g_testMux and delay 100 ticks.\n");
    /* 任务休眠100 ticks */
    osDelay(100);

    printf("task2 resumed and post the g_testMux\n");
    /* 释放互斥资源 */
    osMutexRelease(g_testMux);
    osThreadSuspend(g_testTaskId02);
}

// 修改返回类型为void（适配CMSIS要求）
void Example_TaskEntry(void) {
    /* 创建互斥锁属性配置 */
    osMutexAttr_t mutex_attr = {
        .name = "TestMutex",
        .attr_bits = osMutexRobust  // 设置健壮互斥锁
    };

    /* 创建互斥锁 */
    g_testMux = osMutexNew(&mutex_attr);
    if (g_testMux == NULL) {
        printf("Mutex create failed!\n");
        return;
    }

    /* 锁任务调度 */
    osKernelLock();

    /* 任务属性配置 */
    osThreadAttr_t task_attr = {
        .name = "task1",
        .stack_size = 1024,  // 根据实际内存调整
        .priority = osPriorityNormal  // 使用标准优先级
    };

    /* 创建任务1 */
    g_testTaskId01 = osThreadNew(Example_MutexTask1, NULL, &task_attr);
    if (g_testTaskId01 == NULL) {
        printf("task1 create failed!\n");
        osMutexDelete(g_testMux);
        osKernelUnlock();
        return;
    }

    /* 创建任务2（调整优先级） */
    task_attr.priority = osPriorityAboveNormal;  // 确保优先级低于任务1
    task_attr.name = "task2";
    g_testTaskId02 = osThreadNew(Example_MutexTask2, NULL, &task_attr);
    if (g_testTaskId02 == NULL) {
        printf("task2 create failed!\n");
        osThreadTerminate(g_testTaskId01);
        osMutexDelete(g_testMux);
        osKernelUnlock();
        return;
    }

    /* 解锁任务调度 */
    osKernelUnlock();

    /* 主任务休眠300 ticks */
    osDelay(300);

    /* 清理资源 */
    osMutexDelete(g_testMux);
    osThreadTerminate(g_testTaskId01);
    osThreadTerminate(g_testTaskId02);
}

APP_FEATURE_INIT(Example_TaskEntry);